package br.unifacs.mda.plugin.main.popup.actions;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.xml.sax.SAXException;

import br.unifacs.mda.plugin.code.generator.CodeGeneratorContent;
import br.unifacs.mda.plugin.code.generator.CodeGeneratorIF;
import br.unifacs.mda.plugin.code.generator.impl.CodeGenerator;
import br.unifacs.mda.plugin.exception.ImporterException;
import br.unifacs.mda.plugin.exception.PimGeneratorException;
import br.unifacs.mda.plugin.psm.java.importation.impl.XMIImporterJava;
import br.unifacs.mda.plugin.util.Messages;

public class GenerateJavaCodeAction implements IObjectActionDelegate {

	private Shell shell;
	private IFile psmJavaFile;
	private IProject project;

	/**
	 * Constructor for Action1.
	 */
	public GenerateJavaCodeAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();

		IStructuredSelection sel = (IStructuredSelection) targetPart.getSite()
				.getSelectionProvider().getSelection();
		this.psmJavaFile = (IFile) sel.getFirstElement();
		this.project = this.psmJavaFile.getProject();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {

		XMIImporterJava importerJava = new XMIImporterJava(this.psmJavaFile
				.getLocation().toString(), false);
		CodeGeneratorIF generator = new CodeGenerator(this.project.getFolder(
				"src").getLocation().toString());
		CodeGeneratorContent contentJava = new CodeGeneratorContent(generator);
		try {
			importerJava.start();
			contentJava.start();
			this.project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (ImporterException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {			
			e.printStackTrace();
		} catch (PimGeneratorException e) {
			e.printStackTrace();
		} catch (Exception e) {			
			e.printStackTrace();
		}	
		MessageDialog.openInformation(shell, "MDA Plug-in",
				Messages.CODE_GERADO_SUCESSO);
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}	
}
